package org.gary.core.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;
import org.gary.base.model.Image;

import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import lengreen.util.constant.Constant;

/**
 * 工具类
 * @author lengreen
 * 
 */
public class Utils {
	public static final int BUFFER_SIZE = 200 * 1024;

	/**
	 * 按照yyyy-mm-dd hh:mm:ss格式化一个时间
	 * @param date
	 * @return
	 */
	public static String getFormatDate(Date date, String formatTemplate) {
		SimpleDateFormat format = new SimpleDateFormat(
				Constant.DateFomaterString.YYYY_MM_DD_HH_MM_SS);
		return format.format(date);
	}

	/**
	 * 字符串化一个数组
	 * @param o 要toString的数组
	 * @return 结果String
	 */
	public static String arrayToString(Object[] o) {
		String s = "";
		if (o.length >= 1) {
			for (int i = 0; i < o.length; i++) {
				s += o[i].toString() + ",";
			}
		}
		if (s.length() > 1) {
			s = s.substring(0, s.length() - 1);
		}
		return s;
	}

	/**
	 * 格式化json中的date类型的数据
	 * @param formateString
	 * @return
	 */
	public static JsonConfig makeDateFormateJsonConfig(String formateString) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setIgnoreDefaultExcludes(false);
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor(formateString));
		return jsonConfig;
	}

	/**
	 * 用于将上传文件写入硬盘的
	 * @param src
	 * @param dst
	 * @return
	 */
	public static boolean copy(File src, File dst, int size) {
		boolean result = false;
		InputStream in = null;
		OutputStream out = null;
		try {
			if (!dst.exists()) {
				dst.createNewFile();
			}
			in = new BufferedInputStream(new FileInputStream(src), size);
			out = new BufferedOutputStream(new FileOutputStream(dst), size);
			byte[] buffer = new byte[size];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			result = false;
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/**
	 * 上传多个文件处理方法
	 * @param uploadFiles
	 * @param fileName
	 * @param parentPath
	 * @param buffered
	 * @return
	 */
	public static Set<Image> handleImagesUpload(File[] uploadFiles,
			String[] fileName, String parentPath, int buffered) {
		System.out.println("uploadFiles-->" + uploadFiles);
		if (uploadFiles == null) {
			return null;
		}
		Set<Image> images = new HashSet<Image>();
		java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
		String datearry[] = date.toString().split("-");
		for (int i = 0; i < uploadFiles.length; i++) {
			String filename = UUID.randomUUID().toString() + "."
					+ fileName[i].substring(fileName[i].indexOf(".") + 1);
			String webimagepath = parentPath + "/" + datearry[0] + "/"
					+ datearry[1] + "/" + datearry[2];
			String savepath = ServletActionContext.getServletContext()
					.getRealPath("") + "/" + webimagepath;
			File dstFile = new File(savepath);
			if (!dstFile.exists()) {
				dstFile.mkdirs();
			}
			dstFile = new File(savepath, filename);
			if (Utils.copy(uploadFiles[i], dstFile, buffered)) {
				Image image = new Image();
				image.setPath(webimagepath + "/" + filename);
				image.setName(filename);
				images.add(image);
			}
		}
		return images;
	}
	
	/**
	 * 上传单个文件处理方法
	 * @param uploadFiles
	 * @param fileName
	 * @param parentPath
	 * @param buffered
	 * @return
	 */
	public static Image handleImageUpload(File uploadFile,
			String fileName, String parentPath, int buffered) {
		System.out.println("uploadFiles-->" + uploadFile);
		if (uploadFile == null) {
			return null;
		}
		java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
		String datearry[] = date.toString().split("-");
		String filename = UUID.randomUUID().toString() + "."
				+ fileName.substring(fileName.indexOf(".") + 1);
		String webimagepath = parentPath + "/" + datearry[0] + "/"
				+ datearry[1] + "/" + datearry[2];
		String savepath = ServletActionContext.getServletContext()
				.getRealPath("") + "/" + webimagepath;
		File dstFile = new File(savepath);
		if (!dstFile.exists()) {
			dstFile.mkdirs();
		}
		dstFile = new File(savepath, filename);
		Image image = null;
		if (Utils.copy(uploadFile, dstFile, buffered)) {
			image = new Image();
			image.setPath(webimagepath + "/" + filename);
			image.setName(filename);
		}
		return image;
	}
	
	/**
	 * 二进制转中文
	 * @param binaryString
	 * @return
	 */
	public String binary2CH(String binaryString) {
		String str = Long.toHexString(Long.parseLong(binaryString, 2));
		StringBuffer ch = new StringBuffer();
		for (int i = 0; i + 4 <= str.length(); i = i + 4) {
			int j = Integer.parseInt(str.substring(i, i + 4), 16);
			ch.append((char) j);
		}
		return ch.toString();
	}
	
	/**
	 * 二进制转字符
	 * @param binaryString
	 * @return
	 */
	public String binary2Str(String binaryString) {
		String str = Long.toHexString(Long.parseLong(binaryString, 2));
		StringBuffer ch = new StringBuffer();
		for (int i = 0; i + 4 <= str.length(); i = i + 4) {
			int j = Integer.parseInt(str.substring(i, i + 4), 16);
			ch.append((char) j);
		}
		return ch.toString();
	}
	
	/**
	 * 初始化一个页码
	 * @param start
	 * @return
	 */
	public static int parseIndex(int start, int limit) {
		if(start == 0) {
			return 1;
		} else {
			return 1 + (start / limit);
		}
	}
}
